import { createContext, useCallback, useEffect, useState } from 'react';

export type LoginForm = {
    phone: string;
    code: string;
};
export type LoginFormContextType = {
    loginForm: LoginForm;
    valChange: Function;
    validateTips: string;
    validatePhone: Function;
    setValidateTips: Function;
};
export const LoginFormContext = createContext<LoginFormContextType>(undefined);
const useLoginForm = () => {
    const [loginForm, setloginForm] = useState({
        phone: '',
        code: '',
    });
    const [validateTips, setValidateTips] = useState('');

    const valChange = useCallback(
        (field, event) => {
            const newState = { ...loginForm };
            newState[field] = event.target.value;
            setloginForm(newState);
        },
        [loginForm]
    );
    const validatePhone = useCallback((val) => {
        const regExp_phoneNumber = new RegExp(/^(\+?0?86\-?)?1[3456789]\d{9}$/);
        if (!val) return setValidateTips('');
        if (!regExp_phoneNumber.test(val)) {
            return setValidateTips('请输入正确的手机号格式');
        }
        return setValidateTips('');
    }, []);
    return {
        loginForm,
        valChange,
        validateTips,
        validatePhone,
        setValidateTips,
    };
};

export { useLoginForm };
